/*
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2024-01-05 09:24:42
 * @LastEditors: 2112778581 2112778581@qq.com
 * @LastEditTime: 2024-01-05 09:48:05
 * @FilePath: \my-sjksh\canvas\drawTree\drawTree.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Vector2D } from "../../common/vertor2D.js";
const canvas = document.querySelector("canvas");

const ctx = canvas.getContext("2d");

ctx.translate(0, canvas.height);
ctx.scale(1, -1);

ctx.lineCap = "round";

/**
 *
 * @param {*} context canvas 上下文
 * @param {*} v0 是起始向量
 * @param {*} length 当前树汁的长度
 * @param {*} thickness 当前树枝的粗细
 * @param {*} dir 当前树枝的方向, 用x轴夹角
 * @param {*} bias 随机偏向因子,用来让树枝的朝向有一定的随机性
 */
function drawBranch(context, v0, length, thickness, dir, bias) {
  const v = new Vector2D().rotate(dir).scale(length);
  const v1 = v0.copy().add(v);

  context.lineWidth = thickness;
  context.beginPath();
  context.moveTo(...v0);
  context.lineTo(...v1);
  context.stroke();

  if (thickness > 2) {
    const left = Math.PI / 4 + 0.5 * (dir + 0.2) + bias * (Math.random() - 0.5);
    drawBranch(context, v1, length * 0.9, thickness * 0.8, left, bias * 0.9);
    const right =
      Math.PI / 4 + 0.5 * (dir - 0.2) + bias * (Math.random() - 0.5);
    drawBranch(
      context,
      v1,
      length * 0.9,
      thickness * 0.8,
      right,
      bias * (Math.random() - 0.5)
    );
  }

  if (thickness < 5 && Math.random() < 0.5) {
    context.save();
    context.strokeStyle = "#c72c36";
    const th = Math.random() * 6 + 3;
    context.lineWidth = th;
    context.beginPath();
    context.moveTo(...v1);
    context.lineTo(v1.x, v1.y - 2);
    context.stroke();
    context.restore();
  }
}

const v0 = new Vector2D(256, 0);
drawBranch(ctx, v0, 50, 10, 1, 3);
